<script setup lang="ts">
import { reactive, ref } from 'vue'
import { useUserStore } from '@store/user'
import LoginRegisterOuter from '@components/login-register-outer/index.vue'
import { useRouter } from 'vue-router'
// import { ElMessage } from 'element-plus'
import { register } from '@/api/user'
import { validateUserRegister } from '@/utils/user'
import type { UserRegister } from '@interface'

const router = useRouter()
const userStore = useUserStore()

const userForm = reactive<UserRegister>({
  account: '',
  password: '',
})

const loading = ref(false)
const isRegisterSuccess = ref(false)

const account = ref('')
const handleRegister = async () => {
  const { val, key } = validateUserRegister({
    account: userForm.account,
    password: userForm.password,
  })
  if (!val) throw new Error(`key -> ${key} is required!`)
  loading.value = true
  try {
    const result = await register(userForm)
    loading.value = false
    // 存储token和用户信息
    userStore.updateUserInfo(result)
    router.push('/')
    // if (result.account) {
    //   account.value = result.account
    // }
    // isRegisterSuccess.value = true
  } catch (e) {
    loading.value = true
  }
}

const toLogin = () => {
  router.push({
    path: '/login',
    query: {
      account: account.value,
    },
  })
}

// const copyAccountAndToLogin = async () => {
//   try {
//     await navigator.clipboard.writeText(account.value)
//     toLogin()
//   } catch (e) {
//     ElMessage.error('复制账号失败，请手动复制')
//     toLogin()
//   }
// }
</script>

<template>
  <LoginRegisterOuter
    @on-enter="handleRegister"
    v-loading.fullscreen.lock="loading"
    element-loading-text="注册中"
  >
    <ElInput placeholder="取一个自己喜欢的昵称吧" v-model="userForm.account" />
    <ElInput
      placeholder="请输入密码，记得保存好哦"
      type="password"
      v-model="userForm.password"
    />
    <ElButton class="submit-button" type="primary" @click="handleRegister">
      注册
    </ElButton>
    <div class="to-button">
      <span @click="toLogin">已有账号，去登陆</span>
    </div>
  </LoginRegisterOuter>
</template>
